<template>
  <div class="information">
    <div style="background-color: #fff;">
      <el-form :model="queryForm" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="客户电话:">
              <el-input v-model="queryForm.customerId" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户姓名:">
              <el-input v-model="queryForm.customerName" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="论文审核状态:">
              <el-select
                v-model="queryForm.thesisStatus"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in thesisStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button plain @click="query">查询</el-button>
            <el-button plain @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table :data="tableData" ref="tableRef" style="width: 100%;">
      <el-table-column align="center" fixed prop="customerId" label="客户电话" width="90" />
      <el-table-column align="center" prop="customerName" label="客户姓名" width="90" />
      <el-table-column align="center" prop="thesisTitle" label="论文题目" width="100" />
      <el-table-column align="center" prop="thesisStatus" label="论文审核状态" />
      <el-table-column align="center" prop="process" label="处理说明"/>
      <el-table-column align="center" prop="processDay" label="处理天数" width="80" />
      <el-table-column align="center" prop="processTime" label="处理时间" width="120" />
      <el-table-column align="center" prop="thesisUpdate" label="论文是否上传">
        <template #default="scope">
          <div v-if="scope.row.thesisUpdate==false">否</div>
          <div v-else>是</div>
        </template>
      </el-table-column>  
      <el-table-column align="center" prop="fileName" label="客户文件"/>
      <el-table-column align="center" prop="thesisName" label="论文文件"/>
      <el-table-column align="center" prop="notes" label="客户备注"  />
      <el-table-column align="center" fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button v-if="scope.row.thesisStatus=='待审核'||scope.row.thesisStatus=='已通过'?false:true" 
            link type="primary" size="small" @click="uploadClick(scope.row)">
            上传论文
          </el-button>
          <el-button link type="primary" size="small" @click="downlodeClick(scope.row)">下载论文</el-button>
          <!-- <el-button link type="primary" size="small">查看论文</el-button> -->
          <el-button link type="primary" size="small" @click="downlodesClick(scope.row)">下载客户文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @current-change="currentChange"
        :current-page="pageing.page" 
        :page-size="pageing.size"
        :total="pageing.total"
        style="float: right"
        layout=" prev, pager, next"
      />
    </div>
    <el-dialog
      v-model="editDialogVisible"
      title="上传论文"
      width="800"
      :before-close="handleClose"
      align-center
    >
      <el-form :model="userForm" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item prop="customerId" label="客户电话:">
              <el-text>{{userForm.customerId}}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="customerName" label="客户姓名:">
              <el-text>{{userForm.customerName}}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="thesisTitle" label="论文题目:">
              <el-text line-clamp="2">{{userForm.thesisTitle}}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="thesisStatus" label="论文审核状态:">
              <el-text>{{userForm.thesisStatus}}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="notes" label="客户备注:">
              <el-text>{{userForm.notes}}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上传论文文件:" prop="thesisPath"> 
              <el-upload
                v-model:file-list="fileList"
                ref="uploadRef"
                class="upload-demo"
                action="http://192.168.112.160:8880/api/commerce/v2/client/upload"
                :headers="headersObj"
                :auto-upload="false"
                :on-success="handleSuccess"
                :on-error="handleError"
                :limit="1"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :on-change="handleChange"
              >
                <el-button type="primary">选择文件</el-button>
                <div class="el-upload__tip">
                  仅支持 jpg/png 文件，且不超过 500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item prop="processDay" label="处理天数:">
              <el-input type="number" v-model="userForm.processDay" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item prop="process" label="处理说明:">
              <el-input v-model="userForm.process" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="editUserClick(userForm)">
            提交
          </el-button>
          <el-button @click="cancellClick">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="information">
  import {ref,reactive,onMounted,getCurrentInstance,onActivated} from 'vue'
  import { thesisList,thesisEdit,thesisDownload } from "@/api/modules/upload";
  import { ElNotification } from 'element-plus'
  import { useUserStore } from "@/stores/modules/user"; // 导入用户状态管理store
  const userStore = useUserStore(); // 获取用户状态管理store实例
  const headersObj = {
    "Authorization": 'Bearer ' + userStore.token,    // JWT认证，携带token
  }
  // 论文修改
  const userForm = reactive({
    customerId: '',
    customerName: '',
    thesisTitle: '',
    thesisStatus: '',
    process: '',
    processDay: '',
    processTime: '',
    thesisName:"",
    thesisPath:"",
    notes: '',
    fileName: '',
    filePath: '',
  })
  // 上传弹窗控制值
  const editDialogVisible = ref(false)
  // el-table支持鼠标横向拖拽滚动
  const { proxy } = getCurrentInstance()
  const tableRef = ref()
  nextTick(() => {
    if (tableRef.value) {
      proxy.$dragTable(tableRef)
    }
  })
  // 所属阶段表格
  const tableData = reactive([]);
  const tableDataed = reactive([]);
  // 论文审核状态列表
  const thesisStatusList = reactive([
    {
      value: '未提交',
      label: '未提交',
    },
    {
      value: '待审核',
      label: '待审核',
    },
    {
      value: '待修改',
      label: '待修改',
    },
    {
      value: '已通过',
      label: '已通过',
    },
  ])
  // 查询表单
  const queryForm = reactive({
    customerId: '',
    customerName: '',
    thesisStatus:'',
  })
  // 缓存文件上传
  const uploadRef = ref(null);
  // 定义分页字段
  const pageing = ref({
    total:0,
    page:1,
    size:5,
  })
  // 选择第几页
  const currentChange = (val)=> {
    console.log("翻页，当前为第几页", val);
    tableData.length=0;
    for(let i=0;i<5;i++){
      console.log(tableDataed[(val-1)*5+i]); 
      if(tableDataed[(val-1)*5+i]){
        tableData.push(tableDataed[(val-1)*5+i])
      }
    } 
    pageing.value.page = val;
    console.log(pageing.value.total);
  }
  // 显示已上传的客户文件信息
  const fileList = ref([]);;
  // 限制只能上传一个文件
  const handleExceed = (files, fileList)=>{
    ElNotification({
      title: "文件上传",
      message: "只允许上传一个文件,如需上传最新文件需删除原文件",
      type: "error",
      duration: 2000
    })
  }
  // 文件列表删除触发
  const handleRemove = (file, uploadFiles) => {
    fileList.value = [];
  }
  // 上传成功后的处理修改提交
  const handleSuccess = (response, file) => {
    console.log(fileList.value[0]);
    if(fileList.value[0].name == userForm.fileName){
      userForm.thesisPath = response.data.filepath;
      userForm.thesisName = response.data.filename;
      handleSuccessFun();
    }else {
      const oldFilepath = userForm.thesisPath;
      const oldFilename = userForm.thesisName;
      userForm.thesisPath = response.data.filepath;
      userForm.thesisName = response.data.filename;
      handleSuccessFun({oldFilepath,oldFilename})
    }
  }; 
  // 上传失败后的处理 
  const handleError = (error, file, fileList) => { 
    console.error(error); 
    ElNotification({
      title: "文件上传",
      message: "文件上传失败",
      type: "error",
      duration: 1000
    })
  }; 
  // 监听上传时触发
  const handleChange = (files)=>{
    fileList.value = [{"name":files.name,"url":""}];
  }
  // 上传文件打开弹窗
  const uploadClick = (user) => {
    console.log(user)
    editDialogVisible.value=true;
    if(!user.thesisName){
      fileList.value = [];
      Object.assign(userForm,user);
      return;
    }
    fileList.value = [{"name":user.fileName,"url":user.filePath}];
    Object.assign(userForm,user);
  }
  // 上传文件中提交
  const editUserClick = async(user) =>{
    console.log(user);
    if(fileList.value.length==0){
      // 删除无上传
      ElNotification({
        title: "论文上传信息",
        message: "请上传文件",
        type: "error",
        duration: 1000
      });
      editDialogVisible.value=true;
      return;
    }else {
      // 删除文件上传提交
      const thesisPath= await uploadRef.value.submit()
    }
  }
  // 修改取消
  const cancellClick = ()=>{
    editDialogVisible.value=false;
    fileList.value = [];
  }
  // 下载论文文件
  const downlodeClick = async(user)=>{
    const data = await thesisDownload({"filePath":user.thesisPath,"fileName":user.thesisName});
  }
  // 下载客户文件
  const downlodesClick = async(user)=>{
    const data = await thesisDownload({"filePath":user.filePath,"fileName":user.fileName});
  }
  // 默认加载论文管理
  onActivated(()=>{
    thesisFun();
  })
  // 1.执行获取论文管理列表接口
  const thesisFun = async()=>{
    const { data } = await thesisList();
    // Object.assign(tableData,data);
    tableDataed.length=0
    Object.assign(tableDataed,data);
    pageing.value.total = data.length;
    currentChange(1)
  }
  // 查询
  const query = async() =>{
    const { data } = await thesisList({...queryForm});
    // tableData.length = 0;
    // Object.assign(tableData,data);
    tableDataed.length=0
    Object.assign(tableDataed,data);
    pageing.value.total = data.length;
    currentChange(1)
  }
  // 重置
  const reset = () =>{
    const obj = {
      customerId: '',
      customerName: '',
      thesisStatus:'',
    }
    Object.assign(queryForm,obj);
    thesisFun();
  }
  // 封装修改调接口
  const handleSuccessFun = async(obj) =>{
    let data;
    if(obj){
       data = await thesisEdit({...userForm,...obj});
    }else{
       data = await thesisEdit({...userForm});
    }
    if(data.code == 200){
      cancellClick()
      ElNotification({
        title: "客户信息",
        message: "客户信息修改成功",
        type: "success",
        duration: 1000
      });
      thesisFun();
    }else{
      cancellClick();
      ElNotification({
        title: "客户信息",
        message: "客户信息修改失败",
        type: "error",
        duration: 1000
      });
    }
  }
  // 空白取消
  const handleClose = (done) => {
    ElMessageBox.confirm('您确定要关闭此对话框吗?')
      .then(() => {
        cancellClick();
        done()
      })
      .catch(() => {
        // catch error
      })
  }
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
